#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>

namespace Server
{
    using namespace std;

    static const string defaultIp = "0.0.0.0";
    static const int gnum = 1024;

    class udpServer
    {
    public:
        udpServer(const uint16_t &port, const string &ip = defaultIp)
            : _port(port), _ip(ip), _sockfd(-1)
        {
        }
        void initServer()
        {
            // 1. 创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(-1);
            }
            cout << "socket success: "
                 << " : " << _sockfd << endl;

            // 2. 绑定port，ip(TODO)
            struct sockaddr_in local;
            bzero(&local, sizeof(local));//类似memset设置全0
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            // local.sin_addr.s_addr = inet_addr(_ip.c_str());
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                cerr << "bind error: " << errno << " : " << strerror(errno) << endl;
                exit(-1);
            }
        }
        void start()
        {
            for (;;)
            {
                // 读取数据
                char buffer[gnum];
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (s > 0)
                {
                    int fd = open("data.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
                    if(fd == -1) { cerr << "open error: " << errno << " : " << strerror(errno) << endl; exit(-1); }   
                    write(fd, buffer, strlen(buffer));
                    close(fd);

                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr); // int->点分十进制IP
                    uint16_t clientport = ntohs(peer.sin_port);
                    string message = buffer;
                    cout << clientip << "[" << clientport << "]# " << message << endl;
                }

            }
        }
        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
    };
}
